import 'dart:async';
import 'dart:io';

import 'package:flame_audio/flame_audio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:getwidget/getwidget.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:points24/GameHelper.dart';
import 'package:points24/db/GameData.dart';
import 'package:points24/domain/express.dart';
import 'package:points24/ext_widget/widget_util.dart';
import 'package:points24/history_page.dart';
import 'package:points24/how2play.dart';
import 'package:points24/utils/uihelper.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    /*
    ///Android沉浸式状态栏
    SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle(
      statusBarColor: Colors.transparent, // 设置状态栏颜色为透明
    ));
   */

    return ScreenUtilInit(
      designSize: const Size(375, 812),
      minTextAdapt: true,
      splitScreenMode: true,
      builder: (context, child) {
        return MaterialApp(
          title: '24 Points',
          debugShowCheckedModeBanner: false,
          theme: ThemeData.dark(),
          home: MyHomePage(title: '24 Points'),
        );
      },
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);
  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> with SingleTickerProviderStateMixin {
  late AnimationController animationController;

  var rawNo = List<int>.of([]); //生成的原始数据
  var metaDatas = <Map<String, dynamic>>[]; //首次生成的4个数字
  var expressDatas = <GameExpress>[]; //结果表达式列表
  var expressSteps = <GameExpress>[]; //计算步骤（点击结果集合之后）,用于记录计算过程

  Map<String, dynamic>? lastMeNode; //最后一个接受拖拽的数据
  int targetValue = 24; //计算目标
  bool hideCover = true; //是否隐藏遮挡层（计算的结果集或者提示）

  static const String tipChooseResult = "Choose result?";
  static const String tipWin = "You win!";
  String coverLabel = tipChooseResult;
  bool isSuccessDone = false; //是否成功结束
  int successCount = 0;
  int totalCount = 0;

  int singleTimeMM = 0; //单次游戏的毫秒数
  int totalTimeMM = 0; //本次总毫秒数

  late AudioPool pool; //声音播放器
  Timer? timer; //计时器
  bool isPlaying = false; //是否正在进行中
  bool haveMusic = true; //是否有音乐
  bool hasUnDone = false; //是否有未完成的计算

  startTimer() {

    singleTimeMM = 0;
    timer?.cancel();
    timer = Timer.periodic(const Duration(milliseconds: 100), (timer) {
      singleTimeMM = singleTimeMM + 100;
      setState(() {});
    });

  }

  stopTimer() {
    timer?.cancel();
  }

  @override
  void initState() {
    super.initState();

    Future.delayed(const Duration(milliseconds: 500), () {
      // refresh();
      showInitMyDialog(this.context);
    });

    Future.delayed(const Duration(milliseconds: 1000), () async {
      var allDatas = await GameData.readAllData();
      if (null != allDatas) {
        for (var value in allDatas) {
          if (value.isSuccess() == false) {
            hasUnDone = true;
            setState(() {});
            break;
          }
        }
      }
    });

    animationController = AnimationController(vsync: this, duration: const Duration(milliseconds: 500));
    initBgmMusic();
  }

  void initBgmMusic() {
    FlameAudio.bgm.initialize();
  }

  void playBgm() {
    if (haveMusic) {
      FlameAudio.bgm.play('bgm.mp3');
    }
  }

  void play(String fileName, {double value = 3}) {
    if (haveMusic) {
      FlameAudio.play(fileName, volume: value);
    }
  }

  void stopBgm() {
    FlameAudio.bgm.pause();
  }

  void fireTwo() {
    pool.start();
  }

  @override
  Widget build(BuildContext context) {
    double deviceWidth = MediaQuery.of(context).size.width;
    double rw = deviceWidth * 0.9 / 2;
    double rh = rw;

    return Scaffold(
      // backgroundColor: Colors.white,
      body: Container(
        alignment: Alignment.center,
        // color: Colors.red,
        padding: EdgeInsets.only(top: 50.h),
        decoration: const BoxDecoration(
          image: DecorationImage(
            image: AssetImage('images/bg_game.png'), // 使用你的图片路径
            fit: BoxFit.fitHeight, // 根据需要调整图片的适应方式
          ),
        ),
        child: Stack(
          alignment: Alignment.center,
          children: [
            Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Container(
                    margin: EdgeInsets.only(left: 10.w, right: 10.w, top: 10.w),
                    decoration: BoxDecoration(color: Colors.blue, borderRadius: BorderRadius.circular(5)),
                    width: double.infinity,
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        SizedBox(
                          width: 10.w,
                        ),
                        Transform.rotate(angle: 3.14, child: Icon(Icons.logout)).prop(onTap: () {
                          showExitDialog(context, () {
                            exit(0);
                          });
                        }),
                        SizedBox(
                          width: 10.w,
                        ),
                        GestureDetector(onTapUp: (i) {
                          //跳转到帮助页面
                          if(isPlaying){
                            GFToast.showToast("Pause game first.", context,toastPosition: GFToastPosition.CENTER);
                          }else{
                            Navigator.of(context).push(MaterialPageRoute(builder: (context) => How2Play()));
                          }
                        }, child: const Icon(Icons.help)),
                        SizedBox(
                          width: 10.w,
                        ),
                        Expanded(
                          child: Center(
                            child: Text(
                              "Enjoy compute!",
                              style: GoogleFonts.hachiMaruPop(fontSize: 16.sp, fontWeight: FontWeight.w600, color: Colors.white),
                            ),
                          ),
                        ),
                        GestureDetector(
                          child: Icon(
                            haveMusic ? Icons.music_note_outlined : Icons.music_off_outlined,
                            size: 30.w,
                          ),
                          onTapUp: (x) {
                            haveMusic = !haveMusic;
                            if (haveMusic) {
                              FlameAudio.bgm.resume();
                            } else {
                              stopBgm();
                            }
                            setState(() {});
                          },
                        ),
                        SizedBox(
                          width: 20.w,
                        ),
                        Container(
                          alignment: Alignment.center,
                          child: Stack(children: [
                            Icon(
                              Icons.menu,
                              color: Colors.white,
                              size: 40.w,
                            ),
                            Positioned(
                              right: 4.w,
                              top: 5.w,
                              child: Offstage(
                                offstage: !hasUnDone,
                                child: Container(
                                  width: 10.w,
                                  height: 10.w,
                                  decoration: BoxDecoration(color: Colors.red, borderRadius: BorderRadius.circular(5.r)),
                                ),
                              ),
                            )
                          ]),
                        ).prop(onTap: () async {
                          // GameData.readAllData();
                          debugPrint("---------->>>");

                          if (isPlaying) {
                            GFToast.showToast("Pause game first.", context, toastPosition: GFToastPosition.CENTER);
                            return;
                          }

                          var argument = await Navigator.of(context).push(MaterialPageRoute(builder: (context) => HistoryPage()));
                          if (null != argument) {
                            debugPrint("------->>>>> ${argument}");
                            List<int> newRowNo = argument['rowNo'].cast<int>();

                            showTryAgain(context, newRowNo, () {
                              refresh(false, newRawNo: newRowNo);
                            });
                          }
                        }),
                      ],
                    )),

                SizedBox(
                  height: 10.h,
                ),
                createGameInfoAreaView(20),
                Container(
                  margin: EdgeInsets.only(left: 10.w, right: 10.w, top: 10.w),
                  width: double.infinity,
                  height: 40.h,
                  alignment: Alignment.center,
                  decoration: UIHelper.createMainDecration(Colors.amberAccent),
                  child: Text(
                    "Compute Target: ${targetValue.toInt()}",
                    style: UIHelper.createMainTextStyle(fontSize: 25, color: Colors.black),
                  ),
                ),

                ///记录原始数据
                Container(
                  height: 30.h,
                  width: double.infinity,
                  alignment: Alignment.center,
                  color: Colors.blue,
                  margin: EdgeInsets.only(left: 10.w, right: 10.w, top: 10.w),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      Text(
                        "No：",
                        style: GoogleFonts.poppins(fontSize: 15.sp, fontWeight: FontWeight.w700, color: Colors.white),
                      ),
                      Container(
                        alignment: Alignment.center,
                        height: 100,
                        child: ListView(
                          shrinkWrap: true,
                          scrollDirection: Axis.horizontal,
                          children: metaDatas.map((e) {
                            return AspectRatio(
                              aspectRatio: 1,
                              child: Container(
                                  alignment: Alignment.center,
                                  // decoration: const BoxDecoration(border: Border.fromBorderSide(BorderSide(color: Colors.white, width: 1))),
                                  child: Text(
                                    "${e['no']} ",
                                    textAlign: TextAlign.center,
                                    style: GoogleFonts.poppins(fontSize: 15.sp, fontWeight: FontWeight.w700, color: Colors.white),
                                  )),
                            );
                          }).toList(),
                        ),
                      )
                    ],
                  ),
                ),
                AspectRatio(
                  aspectRatio: 1,
                  child: Stack(
                    alignment: Alignment.center,
                    children: [
                      Container(
                        margin: EdgeInsets.all(5.w),
                        alignment: Alignment.center,
                        // color: Colors.red,
                        child: GridView.count(
                          padding: EdgeInsets.zero,
                          crossAxisCount: 2,
                          mainAxisSpacing: 1.w,
                          crossAxisSpacing: 1.w,
                          childAspectRatio: 1,
                          physics: const NeverScrollableScrollPhysics(),
                          children: List.generate(metaDatas.length, (index) {
                            var metaData = metaDatas[index];

                            ///每个元数据
                            var isDone = metaData['done']; //这个是否已经参与了计算
                            if (isDone) {
                              return Container(
                                width: rw,
                                height: rh,
                                margin: EdgeInsets.all(10.w),
                                decoration: UIHelper.createMainDecration(Colors.grey),
                                child: const Center(
                                    child: Icon(
                                  Icons.gpp_good_sharp,
                                  color: Colors.white,
                                  size: 40,
                                )),
                              );
                            }

                            return Stack(alignment: Alignment.center, children: [
                              Draggable<Map<String, dynamic>>(
                                data: metaDatas[index],
                                onDragStarted: () {
                                  play("press.mp3");
                                },
                                onDragCompleted: () {},
                                onDragUpdate: (DragUpdateDetails details) {},
                                onDragEnd: (DraggableDetails details) {},
                                onDraggableCanceled: (Velocity velocity, Offset offset) {},
                                feedback: Container(
                                  width: rw,
                                  height: rh,
                                  decoration: UIHelper.createMainDecration(metaData['color']),
                                  child: Center(
                                    child: Text(
                                      '${metaData['no']}',
                                      style: UIHelper.createMainTextStyle(),
                                    ),
                                  ),
                                ),
                                childWhenDragging: Container(
                                  width: rw,
                                  height: rh,
                                  decoration: UIHelper.createMainDecration(metaData['color']),
                                  child: Center(
                                    child: Text(
                                      '${metaData['no']}',
                                      style: UIHelper.createMainTextStyle(),
                                    ),
                                  ),
                                ),
                                child: Container(
                                  width: rw,
                                  height: rh,
                                  decoration: UIHelper.createMainDecration(metaData['color']),
                                  child: Center(
                                    child: Text(
                                      '${metaData['no']}',
                                      style: UIHelper.createMainTextStyle(),
                                    ),
                                  ),
                                ),
                              ),
                              DragTarget<Map<String, dynamic>>(onAccept: (received) {
                                //debugPrint("on received---${received} --> ${datas[index]}");
                                onDragReceived(metaDatas[index], received);
                              }, builder: (context, candidateData, rejectedData) {
                                return SizedBox(
                                  width: rw,
                                  height: rh,
                                );
                              }),
                            ]);

                            //     .prop(
                            //   onTap: (){},
                            //   borderRadius: [30]
                            // );
                          }),
                        ),
                      ),
                      Offstage(
                        offstage: hideCover,
                        child: Container(
                          width: double.infinity,
                          height: double.infinity,
                          alignment: Alignment.center,
                          margin: EdgeInsets.only(left: 10.w, right: 10.w, top: 10.w, bottom: 10.w),
                          decoration: UIHelper.createMainDecration(Colors.black.withAlpha(125)),
                          child: Stack(alignment: Alignment.center, children: [
                            Offstage(
                              offstage: !isSuccessDone,
                              child: Image.asset("images/you_win.png").prop(borderRadius: [23.r]),
                            ),
                            Container(
                              alignment: Alignment.center,
                              child: Column(
                                mainAxisAlignment: MainAxisAlignment.center,
                                crossAxisAlignment: CrossAxisAlignment.center,
                                children: [
                                  Container(
                                    margin: EdgeInsets.all(20.w),
                                    child: Text(
                                      coverLabel,
                                      style: UIHelper.createMainTextStyle(fontSize: 30.sp),
                                    ),
                                  ),
                                  Container(
                                    height: 60.h,
                                    width: double.infinity,
                                    margin: EdgeInsets.only(left: 10.w, right: 10.w),
                                    decoration: const BoxDecoration(
                                        borderRadius: BorderRadius.all(Radius.circular(20)),
                                        border: Border.fromBorderSide(BorderSide(color: Colors.amberAccent, width: 2))),
                                    child: Container(
                                      alignment: Alignment.center,
                                      child: SingleChildScrollView(
                                        scrollDirection: Axis.horizontal,
                                        child: Row(
                                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                            crossAxisAlignment: CrossAxisAlignment.center,
                                            children: expressDatas.map<Widget>((e) {
                                              return AspectRatio(
                                                  aspectRatio: 1,
                                                  child: Container(
                                                    decoration: const BoxDecoration(
                                                      color: Colors.amberAccent,
                                                      border: Border.fromBorderSide(BorderSide(color: Colors.blue, width: 1)),
                                                      // gradient: LinearGradient(colors: [Colors.amberAccent,Colors.amber.withAlpha(100)])
                                                      // gradient: RadialGradient(colors: [Colors.blue, Colors.amberAccent])
                                                    ),
                                                    child: Center(
                                                      child: Text(
                                                        "${e.bestResult()}",
                                                        style: GoogleFonts.poppins(
                                                          color: Colors.white,
                                                          fontSize: 18.sp,
                                                          fontWeight: FontWeight.w600,
                                                        ),
                                                      ),
                                                    ),
                                                  )).prop(onTap: () {
                                                onChoseDone(e);
                                              });
                                            }).toList()),
                                      ),
                                    ),
                                  ),
                                  Expanded(
                                    child: Stack(children: [
                                      Offstage(
                                        offstage: !isSuccessDone,
                                        child: Container(
                                          color: Colors.amberAccent,
                                          child: Column(
                                            mainAxisAlignment: MainAxisAlignment.center,
                                            children: [
                                              Container(
                                                height: 40.h,
                                                width: double.infinity,
                                                alignment: Alignment.center,
                                                color: Colors.blue,
                                                child: Row(
                                                  mainAxisAlignment: MainAxisAlignment.center,
                                                  crossAxisAlignment: CrossAxisAlignment.center,
                                                  children: [
                                                    Text(
                                                      "Steps：",
                                                      style: GoogleFonts.poppins(fontSize: 15.sp, fontWeight: FontWeight.w700, color: Colors.white),
                                                    ),
                                                  ],
                                                ),
                                              ),
                                              Column(
                                                mainAxisAlignment: MainAxisAlignment.center,
                                                children: expressSteps.map((e) {
                                                  return Container(
                                                      height: 24.h,
                                                      width: double.infinity,
                                                      alignment: Alignment.center,
                                                      color: Colors.orange,
                                                      child: Text(
                                                        "${e.niceExpress()}",
                                                        style: GoogleFonts.poppins(fontWeight: FontWeight.w600, fontSize: 16.sp, color: Colors.white),
                                                      ));
                                                }).toList(),
                                              ),
                                              Expanded(
                                                child: Center(
                                                  child: SizedBox(
                                                    width: MediaQuery.of(context).size.width / 3,
                                                    child: GFButton(
                                                      fullWidthButton: true,
                                                      size: 50,
                                                      shape: GFButtonShape.pills,
                                                      onPressed: () {
                                                        refresh(true);
                                                      },
                                                      text: "Next",
                                                      textStyle: GoogleFonts.poppins(color: Colors.white, fontSize: 20.sp, fontWeight: FontWeight.w600),
                                                    ),
                                                  ),
                                                ),
                                              )
                                            ],
                                          ),
                                        ).prop(borderRadius: [15.r], margins: [10.w]),
                                      ),
                                    ]),
                                  )
                                ],
                              ),
                            ),
                          ]),
                        ),
                      )
                    ],
                  ),
                ),
                //底部按钮操作区域
                createOperateButtons(),
              ],
            ),
          ],
        ),
      ),
      // This trailing comma makes auto-formatting nicer for build methods.
    );
  }

  SizedBox createOperateButtons() {
    return SizedBox(
      height: 90.h,
      child: Row(
        children: [
          Expanded(
            flex: 1,
            child: Container(
              margin: EdgeInsets.only(left: 10.w, right: 10.w),
              child: GFButton(
                fullWidthButton: true,
                size: 50.h,
                shape: GFButtonShape.pills,
                onPressed: () {
                  onPass();
                },
                child: Text(
                  "Pass",
                  style: GoogleFonts.poppins(color: Colors.white, fontSize: 20.sp, fontWeight: FontWeight.w600),
                ),
              ),
            ),
          ),
          Expanded(
            flex: 1,
            child: Container(
              margin: EdgeInsets.only(left: 10.w, right: 10.w),
              child: GFButton(
                fullWidthButton: true,
                size: 50.h,
                shape: GFButtonShape.pills,
                onPressed: () {
                  reset();
                },
                child: Text(
                  "Reset",
                  style: GoogleFonts.poppins(color: Colors.white, fontSize: 20.sp, fontWeight: FontWeight.w600),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  //底部信息按钮区域
  Widget createGameInfoAreaView(double contentHeight) {
    return Container(
      height: 70.h,
      margin: EdgeInsets.only(left: 10.w, right: 10.w),
      alignment: Alignment.center,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(10),
        color: Colors.amberAccent,
      ),
      child: Row(crossAxisAlignment: CrossAxisAlignment.center, children: [
        Expanded(
          flex: 2,
          child: Container(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Container(
                  height: contentHeight,
                  alignment: Alignment.center,
                  child: Text(
                    "Success/Total",
                    style: UIHelper.createMainTextStyle(fontSize: 14, color: Colors.blue),
                  ),
                ),
                Container(
                  height: contentHeight,
                  alignment: Alignment.center,
                  child: Text(
                    "${successCount}/${totalCount}",
                    style: UIHelper.createMainTextStyle(fontSize: 14, color: Colors.blue),
                  ),
                ),
              ],
            ),
          ),
        ),
        Expanded(
          flex: 2,
          child: Column(
            children: [
              Expanded(
                flex: 1,
                child: Container(
                  // color: Colors.amberAccent,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Container(
                          transformAlignment: Alignment.centerLeft,
                          height: 30.h,
                          alignment: Alignment.center,
                          child: Text(
                            "Time: ",
                            textAlign: TextAlign.start,
                            style: GoogleFonts.poppins(
                              fontWeight: FontWeight.w500,
                              fontSize: 15,
                              color: Colors.black,
                            ),
                          )),
                      Container(
                          transformAlignment: Alignment.centerLeft,
                          height: 30.h,
                          alignment: Alignment.center,
                          child: Text(
                            "${usedTime()}",
                            textAlign: TextAlign.start,
                            style: GoogleFonts.poppins(
                              fontWeight: FontWeight.w500,
                              fontSize: 15,
                              color: Colors.black,
                            ),
                          )),
                    ],
                  ),
                ),
              ),
              Expanded(
                flex: 1,
                child: Container(
                  // color: Colors.amberAccent,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Container(
                          transformAlignment: Alignment.centerLeft,
                          height: 30.h,
                          alignment: Alignment.center,
                          child: Text(
                            "Avg: ",
                            textAlign: TextAlign.start,
                            style: GoogleFonts.poppins(
                              fontWeight: FontWeight.w500,
                              fontSize: 15,
                              color: Colors.black,
                            ),
                          )),
                      Container(
                          transformAlignment: Alignment.centerLeft,
                          height: 30.h,
                          alignment: Alignment.center,
                          child: Text(
                            "${avgUsedTime()}",
                            textAlign: TextAlign.start,
                            style: GoogleFonts.poppins(
                              fontWeight: FontWeight.w500,
                              fontSize: 15,
                              color: Colors.black,
                            ),
                          )),
                    ],
                  ),
                ),
              ),
            ],
          ),
        ),
        Expanded(
            flex: 2,
            child: Center(
              child: AspectRatio(
                aspectRatio: 1,
                child: Container(
                  margin: const EdgeInsets.all(8),
                  child: Container(
                    alignment: Alignment.center,
                    // color: Colors.red,
                    child: createPlayPauseWidget(),
                  ).prop(borderRadius: [50.r], border: const Border.fromBorderSide(BorderSide(color: Colors.white, width: 2))),
                ),
              ),
            ))
      ]),
    );
  }

  ///生成暂停和播放
  Widget createPlayPauseWidget() {
    void callBack(td) {
      isPlaying = !isPlaying;
      if (isPlaying) {
        startGame(isResume: true);
      } else {
        animationController.reverse();
        stopTimer();
        if (haveMusic) {
          FlameAudio.bgm.pause();
        }
        // showPauseDialog(this.context);
      }
      debugPrint("IsPlay -----> ${isPlaying}");
      setState(() {});
    }

    return GestureDetector(
        onTapUp: callBack,
        child: AnimatedIcon(
          icon: AnimatedIcons.play_pause,
          progress: animationController,
          size: 40,
        ));
  }

  usedTime() {
    return "${singleTimeMM / 1000} s";
  }

  avgUsedTime() {
    if (successCount == 0) {
      return "0 s";
    }
    return "${(totalTimeMM / 1000 / successCount).toStringAsFixed(1)} s";
  }

  //计算成功
  onSuccess() {
    stopTimer();

    totalTimeMM += singleTimeMM; //记录总耗时
    isSuccessDone = true;
    successCount++;
    totalCount++;

    GameData.saveSuccessData(rawNo, expressSteps, singleTimeMM);
    play("success.mp3");
  }

  /// 选中候选计算结果之后
  void onChoseDone(GameExpress e) {
    if (e.computeRealValue() == targetValue && justOne(metaDatas)) {
      //中途算出一个24 ，不处理
    } else {
      debugPrint("--->> ${e} - computed-> ${e.computeRealValue()}");
      //计算合并后的结果设置到接受数字的节点
      expressSteps.add(e.clone());
      lastMeNode?['no'] = e.computeRealValue().toInt(); //将新的值赋给接受节点
      expressDatas.clear();
      hideCover = true;
      setState(() {});
    }

    play("confirm.mp3");
  }

  ///收到拖拽
  void onDragReceived(Map<String, dynamic> meNode, Map<String, dynamic> received) {
    //debugPrint("on received---${received} --> ${datas[index]}");
    if (meNode['key'] == received['key'] || (meNode['done'] || received['done'])) {
      return;
    }

    received['done'] = true;
    double me = meNode['no'].toDouble();
    double inCome = received['no'].toDouble();
    debugPrint("received:---${inCome} --> ${me}");

    ///判断是否计算出结果
    var list = GameExpress.createAll(me, inCome);
    bool win = false;

    GameExpress? winExpre;
    for (var expr in list) {
      debugPrint("表达式结果--》${expr} justOne-> ${justOne(metaDatas)}");
      if (justOne(metaDatas) && expr.result == targetValue) {
        winExpre = expr;
        expressSteps.add(expr.clone());
        win = true;
        break;
      }
    }
    if (win) {
      coverLabel = tipWin;
      onSuccess();
    }
    //===============
    expressDatas.clear();
    if (win) {
      expressDatas.add(winExpre!);
    } else {
      expressDatas.addAll(list);
    }

    lastMeNode = meNode;
    hideCover = false;

    debugPrint("--------> win--> ${win} 耗时${usedTime()} ");
    play("receive.mp3");
    setState(() {});
  }

  ///是否只剩下最后一个
  bool justOne(var metaDatas) {
    int doneCount = 0;
    for (var node in metaDatas) {
      if (node['done'] == true) {
        doneCount++;
      }
    }
    if (doneCount == 3) {
      return true;
    } else {
      return false;
    }
  }

  ///pass掉这个计算
  onPass() {
    debugPrint("--->>  ${rawNo}");
    GameData.saveFailData(rawNo, singleTimeMM);
    refresh(true);
  }

  ///刷新:addToTotalCount 本次刷新是否计入总量
  refresh(bool addToTotalCount, {List<int>? newRawNo}) {
    if (addToTotalCount) {
      totalCount++;
    }

    isSuccessDone = false;
    hideCover = true;
    metaDatas.clear();
    expressSteps.clear();
    coverLabel = tipChooseResult;
    expressDatas.clear();
    rawNo.clear();

    if (null != newRawNo) {
      metaDatas.addAll(createRandom4Num(newRawNo: newRawNo));
    } else {
      metaDatas.addAll(createRandom4Num());
    }

    setState(() {});
    startTimer();
    play("press.mp3");
  }

  //生成4个数字
  createRandom4Num({List<int>? newRawNo}) {
    rawNo.clear();
    List<Map<String, dynamic>> data = GameHelper.createInitDate(rawNo, newRawNo: newRawNo);
    return data;
  }

  ///计算重置
  reset() {
    isSuccessDone = false;
    hideCover = true;
    expressSteps.clear();
    expressDatas.clear();
    metaDatas.clear();
    for (var meta in rawNo) {
      //metaDatas.add()
      metaDatas.add(Map.of({"no": meta, "key": UniqueKey(), "color": Colors.amberAccent, "done": false}));
    }

    setState(() {});
    startTimer();
    play("press.mp3");
  }

  void showInitMyDialog(BuildContext context) {
    showDialog(
      barrierDismissible: false,
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          backgroundColor: Colors.white,
          content: Container(
              height: 40.h,
              alignment: Alignment.center,
              child: Text(
                'Start Game or How to play?',
                style: GoogleFonts.poppins(fontSize: 15.sp, fontWeight: FontWeight.w500, color: Colors.blue),
              )),
          actionsAlignment: MainAxisAlignment.spaceBetween,
          actions: <Widget>[
            GFButton(
                shape: GFButtonShape.pills,
                text: 'How to Play',
                textStyle: GoogleFonts.poppins(fontSize: 15.sp, fontWeight: FontWeight.w500, color: Colors.white),
                onPressed: () {
                  // Navigator.of(context).pop();
                  Navigator.of(context).push(MaterialPageRoute(builder: (context) => How2Play()));
                }),
            GFButton(
                shape: GFButtonShape.pills,
                text: 'Start Game',
                textStyle: GoogleFonts.poppins(fontSize: 15.sp, fontWeight: FontWeight.w500, color: Colors.white),
                onPressed: () {
                  Navigator.of(context).pop();
                  startGame(isResume: false);
                }),
          ],
        );
      },
    );
  }

  ///暂定的时候弹出的dialog
  void showPauseDialog(BuildContext context) {
    showDialog(
      barrierDismissible: false,
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          backgroundColor: Colors.white,
          // title: const Text(''),
          content: Container(
            height: 40.h,
            alignment: Alignment.center,
            child: Text(
              'Back to game or exit app?',
              style: GoogleFonts.poppins(fontSize: 15.sp, fontWeight: FontWeight.w500, color: Colors.blue),
            ),
          ),
          actionsAlignment: MainAxisAlignment.spaceBetween,
          actions: <Widget>[
            GFButton(
                shape: GFButtonShape.pills,
                text: 'Exit App',
                textStyle: GoogleFonts.poppins(fontSize: 15.sp, fontWeight: FontWeight.w500, color: Colors.white),
                onPressed: () {
                  Navigator.of(context).pop();
                  exit(0);
                }),
            GFButton(
                shape: GFButtonShape.pills,
                text: 'Back to game',
                textStyle: GoogleFonts.poppins(fontSize: 15.sp, fontWeight: FontWeight.w500, color: Colors.white),
                onPressed: () {
                  Navigator.of(context).pop(); // 关闭对话框
                  startGame(isResume: true);
                }),
          ],
        );
      },
    );
  }

  /// isResume 是否是从暂定过来的
  void startGame({bool isResume = true}) {
    isPlaying = true;
    if (isResume) {
      animationController.forward();
      refresh(false);
      if (haveMusic) {
        FlameAudio.bgm.resume();
      }
    } else {
      playBgm();
      animationController.forward();
      refresh(false);
    }
    setState(() {});
  }

  void showTryAgain(BuildContext context, List<dynamic> rowNo, Function() yesCallBack) {
    showDialog(
      barrierDismissible: false,
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          backgroundColor: Colors.white,
          content: Container(
              height: 60.h,
              alignment: Alignment.center,
              child: Text(
                textAlign: TextAlign.center,
                '${rowNo}\n Compute this now?',
                style: GoogleFonts.poppins(fontSize: 20.sp, fontWeight: FontWeight.w500, color: Colors.blue),
              )),
          actionsAlignment: MainAxisAlignment.spaceBetween,
          actions: <Widget>[
            GFButton(
                shape: GFButtonShape.pills,
                text: 'Cancel',
                color: Colors.grey,
                textStyle: GoogleFonts.poppins(fontSize: 15.sp, fontWeight: FontWeight.w500, color: Colors.black),
                onPressed: () {
                  Navigator.of(context).pop();
                }),
            GFButton(
                shape: GFButtonShape.pills,
                text: 'Yes',
                textStyle: GoogleFonts.poppins(fontSize: 15.sp, fontWeight: FontWeight.w500, color: Colors.white),
                onPressed: () {
                  Navigator.of(context).pop();
                  yesCallBack();
                }),
          ],
        );
      },
    );
  }

  void showExitDialog(BuildContext context, Function() yesCallBack) {
    showDialog(
      barrierDismissible: false,
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          backgroundColor: Colors.white,
          content: Container(
              height: 60.h,
              alignment: Alignment.center,
              child: Text(
                textAlign: TextAlign.center,
                'Exit Game?',
                style: GoogleFonts.poppins(fontSize: 20.sp, fontWeight: FontWeight.w500, color: Colors.blue),
              )),
          actionsAlignment: MainAxisAlignment.spaceBetween,
          actions: <Widget>[
            GFButton(
                shape: GFButtonShape.pills,
                text: 'Yes',
                textStyle: GoogleFonts.poppins(fontSize: 15.sp, fontWeight: FontWeight.w500, color: Colors.white),
                onPressed: () {
                  Navigator.of(context).pop();
                  yesCallBack();
                }),
            GFButton(
                shape: GFButtonShape.pills,
                text: 'Cancel',
                color: Colors.grey,
                textStyle: GoogleFonts.poppins(fontSize: 15.sp, fontWeight: FontWeight.w500, color: Colors.white),
                onPressed: () {
                  Navigator.of(context).pop();
                }),
          ],
        );
      },
    );
  }

  @override
  void dispose() {
    stopTimer();
    animationController?.dispose();
    super.dispose();
  }
}
